<section class="content-header">
  <h1>&nbsp;</h1>
  <ol class="breadcrumb">
    <li><a><i class="fa fa-dashboard"></i>信息管理</a></li>
    <li class="active"><a>设备管理</a></li>
  </ol>
</section>
<!-- Main content -->
<section class="content" id="deviceContent">
  <div class="row">
    <div class="col-xs-12">
      <div class="box">
        <div class="box-body">
			<!-- 搜索条件 -->
			<table class="table" style="border:1px sold red">
				<tr height="45px" bgcolor="#F3F3F3">
				    <td align="left" style="width:150px;">
						<select class="form-control" id="sel_install">
							<option value="all">全部</option>
							<option value="0">未安装</option>
							<option value="1">已安装</option>
						</select>
					</td>
					<td style="width:230px;">
						<input type="text" id="selCompany" class="form-control" name="sel_company" placeholder="选择公司" onclick="$('#treeview').show()" value=""/>
					</td>
				    <td align="left" style="width:250px;">
				        <div class="input-group">
				          <input type="text" id="sel_device_id" class="form-control" placeholder="设备号">
				              <span class="input-group-btn">
				                <button id="searchBtn" name="searchBtn" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i></button>
				              </span>
				        </div>
					</td>
					<td align="left">
						<input type="button" class="btn btn-danger btn-small" value="添加" onclick="showDialog('insert','-1','-1');"/>&nbsp;
						<input type="button" class="btn btn-primary btn-small" value="在线设备"/>&nbsp;
						<input type="button" class="btn btn-primary btn-small" value="未注册设备"/>&nbsp;
						<input type="button" class="btn btn-default btn-small" value="导出至Execl"/>&nbsp;
					</td>
				</tr>
			</table>
			<!-- 结果列表 -->
			<table id="myTableData" class="table table-bordered table-condensed table-hover table-striped">
             <thead>
             <tr>
			   <th>ID</th>
               <th width="50">序号</th>
               <th>设备号</th>
               <th>SIM卡号</th>
               <th>设备序列号</th>
               <th>设备类型</th>
               <th>产品品牌</th>
               <th>产品型号</th>
               <th>所属公司</th>
               <th>安装情况</th>
               <th>安装日期</th>    
               <th>所属车辆</th>
               <th>操作</th>                                 
             </tr>
             </thead>
             <tbody>
              </tbody>
            </table>
         	</div>
       	 </div>
      </div>
   </div>
</section>
<div class="modal fade" id="infoModal">
  <div class="modal-dialog" style="width:800px">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="infoModalTitle"></h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" id="defaultForm">
    		<div class="box-body">
                <table style="width:100%;">
                	<tr>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-3 control-label">设备号</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="device_id" name="device_id" maxlength="50"/>
			                  </div>
			                </div>
                  		</td>
                  		<td>&nbsp;</td>
                     </tr>
                     <tr>
                		<td>
                			<div class="form-group">
			                  <label class="col-sm-3 control-label">所属公司</label>
			                  <div class="col-sm-6">
			                    	<input class="link-url form-control" id="company_name" name="company_name" type="text" onclick="showMenu();" placeholder="选择公司" readonly="true"/>
									<input type="hidden" id="company_id" />
									<div id="menuContent" class="menuContent" style="display:none;position: absolute;z-index:999">
										<ul id="treeDemo" class="ztree"	style="margin-top:0; width:93%;min-height: 215px;"></ul>
									</div>
			                   </div>
			                </div>	                		
                		</td>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-4 control-label">设备类型</label>
			                  <div class="col-sm-6">
			                    <select id="device_type" name="device_type" style="width:170px" class="form-control"></select>
			                  </div>
			                </div>
                  		</td>
                    </tr>
                    <tr>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-3 control-label">SIM卡号</label>
			                  <div class="col-sm-6">
			                    <input type="hidden" class="form-control" id="old_sim_id" disabled/>
			                    <input type="hidden" class="form-control" id="sim_id" disabled/>
			                    <input type="text" class="form-control" id="sim_card" maxlength="50" onClick="openSimList()" readonly="true"/>
			                  </div>
			                  <span class="glyphicon glyphicon-plus" style="cursor: pointer;" onClick="showAddSim()"></span>
			                </div>
                  		</td>		                  		
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-4 control-label">厂家类型</label>
			                  <div class="col-sm-6">
			                    <select id="factory_type" name="factory_type" style="width:170px" class="form-control"></select>
			                  </div>
			                </div>
                  		</td>
                  	</tr>
                    <tr>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-3 control-label">设备序列号</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="serial_id" maxlength="50"/>
			                  </div>
			                </div>
                  		</td>
                  		<td>&nbsp;</td>
                    </tr>		                  	
                  	<tr>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-3 control-label">产品品牌</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="brand" maxlength="50"/>
			                  </div>
			                </div>
                  		</td>		                  		
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-4 control-label">产品型号</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="model" maxlength="50"/>
			                  </div>
			                </div>
                  		</td>
                  	</tr>
                  	<tr>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-3 control-label">软件版本</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="software_ver" maxlength="50"/>
			                  </div>
			                </div>
                  		</td>
      				       <td>
                			<div class="form-group">
                			  <label class="col-sm-4 control-label">硬件版本</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="hardware_ver" maxlength="50"/>
			                  </div>
			                </div>
                  		</td>		                  		
                	</tr>
                  	<tr>
                		<td>
                			<div class="form-group">
                			  <label class="col-sm-3 control-label">产品厂家</label>
			                  <div class="col-sm-6">
			                    <input type="text" class="form-control" id="product_manufacturer" maxlength="100"/>
			                  </div>
			                </div>
                  		</td>
                  		<td>&nbsp;</td>
                	</tr>	
	               	<tr>
	               		<td>
	               			<div class="form-group">
	               			  <label class="col-sm-3 control-label">备注</label>
			                  <div class="col-sm-9">
			                    <textarea class="form-control" rows="8" cols="50" maxlength="500" id="remark"></textarea>
			                  </div>
			                </div>
	                 	</td>
	                 	<td>&nbsp;</td>
	               	</tr>		                		                			                
                </table>
       		</div>
             <div class="box-footer">
             	<div class="pull-right">
             		<input type="hidden" id="infoId"/>
              		<button type="button" class="btn btn-info" id="saveInfoBtn" >保存</button>
                 	&nbsp;&nbsp;&nbsp;&nbsp;
                	<button type="button" class="btn btn-default pull-right" data-dismiss="modal">关闭</button>
             	</div>
             </div>
          </form>
      </div>
    </div>
  </div>
</div>
<!-- Sim卡列表 -->  
<div class="modal fade" id="simListModal">  
  <div class="modal-dialog">  
    <div class="modal-content message_align">  
      <div class="modal-header">  
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>  
        <h4 class="modal-title">选择SIM卡信息</h4>  
      </div>  
      <div class="modal-body">  
	   <div class="input-group" style="width:320px;">
         <input type="text" id="sel_sim_card" class="form-control" placeholder="SIM卡号">
             <span class="input-group-btn">
               <button id="searchBtn" name="searchBtn" class="btn btn-flat" onClick=><i class="fa fa-search"></i></button>
             </span>
       </div>
	   <table id="simList" class="table table-bordered table-condensed table-hover table-striped">
            <thead>
              <tr>
	              <th width="50">序号</th>
	              <th>SIM卡号</th>
	              <th>所属公司</th>
	              <th width="50">操作</th>
              </tr>
            </thead>
            <tbody>
             </tbody>
       </table>
      </div>  
      <div class="modal-footer">  
         <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>  
      </div>  
    </div>
  </div>
</div>
<!-- 增加Sim卡 -->  
<div class="modal fade" id="addSimModal">  
  <div class="modal-dialog">  
    <div class="modal-content message_align">  
      <div class="modal-header">  
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>  
        <h4 class="modal-title">添加SIM卡信息</h4>  
      </div>  
      <form class="form-horizontal" id="fastAddSimForm">
	      <div class="modal-body">  
	            <div class="box-body">
	              <div class="form-group">
	                <label class="col-sm-2 control-label">SIM卡号</label>
	                <div class="col-sm-6">
	                  <input type="text" class="form-control" id="add_sim_card" name="add_sim_card" maxlength="50">
	                </div>
	              </div>
	            </div>
	      </div>  
	      <div class="modal-footer">  
	      	 <input type="hidden"/>
	         <button type="button" class="btn btn-primary" id="saveAddSimBtn">确定</button>
	         <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>  
	      </div> 
      </form> 
    </div>
  </div>
</div>
<script type="text/javascript">
	$(function(){ 
		 $("#myTableData").dataTable({
			  lengthMenu: [10],//这里也可以设置分页，但是不能设置具体内容，只能是一维或二维数组的方式，所以推荐下面language里面的写法。
		      paging: true,//分页
		      ordering: true,//是否启用排序
		      searching: false,//搜索
		      language: {
		    	  lengthMenu: '',//左上角的分页大小显示。
		          paginate: {//分页的样式内容。
		              previous: "上一页",
		              next: "下一页",
		              first: "首页",
		              last: "末页"
		          },
		          zeroRecords: "没有内容",//table tbody内容为空时，tbody的内容。
		          //下面三者构成了总体的左下角的内容。
		          info: "总共_PAGES_ 页，显示第_START_ 到第 _END_条记录 ，记录总数： _TOTAL_条 ",//左下角的信息显示，大写的词为关键字。
		          infoEmpty: "0条记录",//筛选为空时左下角的显示。
		          infoFiltered: ""//筛选之后的左下角筛选提示，
		      },
		      pagingType: "full_numbers",//分页样式的类型
		      "serverSide": true,
		      ajax: function (data, callback, settings) {
		           //封装请求参数
		           var param = {};
		           param.limit = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
		           param.start = data.start;//开始的记录序号
		           param.page = (data.start / data.length)+1;//当前页码
		           param.orderby=data.orderBys;
		           //ajax请求数据
		           $.ajax({
		               type: "post",
		               url: "${request.contextPath}/device/searchList",
		               cache: false,  //禁用缓存
		               data: param,  //传入组装的参数
		               dataType: "json",
		               success: function (result) {
		                   //封装返回数据
		                   var returnData = {};
		                   returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
		                   returnData.recordsTotal = result.total;//返回数据全部记录
		                   returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
		                   returnData.data = result.pageData;//返回的数据列表
		                   callback(returnData);
		               }
		           });
		       },
		       //列表表头字段
		       columns: [
		           { "data": "id" },
                   { "data": null},
		           { "data": "device_id_substr" },
		           { "data": "sim_card" },
		           { "data": "serial_id" },
		           { "data": "device_type_name" },
		           { "data": "brand" },
		           { "data": "model" },
		           { "data": "company_name" },
		           { "data": "install_name" },
		           { "data": "install_time_str" },
		           { "data": "vehid" },
		           { "data": null}
		       ],
             fnDrawCallback  : function(){
                 this.api().column(1).nodes().each(function(cell, i) {
                     cell.innerHTML =  i + 1;
                 });
             },
		       "aoColumnDefs":[
                   {
                       "targets":0,
                       "visible":false
                   },
		           {//倒数第一列
		               "targets":-1,
		               "bSortable": false,
		               render: function(data, type, row) {
		                   var html = '<button class="btn btn-success btn-small" onclick="showDialog(\'update\',\''+data.id+'\',\''+data.install+'\');">编辑</button>&nbsp;&nbsp;&nbsp;&nbsp;';
		                   if(data.install==0){//未安装
		                	  html += '<button class="btn btn-danger btn-small" onclick="deleteInfoInList(\''+data.id+'\');">删除</button>';
		                   }
		                   if(data.install==1){//已安装
		                	  html += '<button class="btn btn-default btn-small" disabled="disabled">删除</button>';
		                   }
		                   return html;
		               }
		           },
		        ]
		   });
      //设备信息表单
	  $('#defaultForm').bootstrapValidator({
	        message: '此值无效',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {
	        	device_id: {
	                validators: {
	                    notEmpty: {
	                        message: '不能为空'
	                    }
	                }
	            },
	            company_name: {
	                validators: {
	                    notEmpty: {
	                        message: '不能为空'
	                    }
	                }
	            }
	        }
	    });
	    $("#saveInfoBtn").on("click", function(){
		    var bootstrapValidator = $('#defaultForm').data('bootstrapValidator');
	        bootstrapValidator.validate();
	        if(bootstrapValidator.isValid()){
	            saveInfo();
	        }
		 });
      //快速增加SIM卡信息表单
	  $('#fastAddSimForm').bootstrapValidator({
	        message: '此值无效',
	        feedbackIcons: {
	            valid: 'glyphicon glyphicon-ok',
	            invalid: 'glyphicon glyphicon-remove',
	            validating: 'glyphicon glyphicon-refresh'
	        },
	        fields: {
	        	add_sim_card: {
	                validators: {
	                    notEmpty: {
	                        message: '不能为空'
	                    }
	                }
	            }
	        }
	    });
	    $("#saveAddSimBtn").on("click", function(){
		    var bootstrapValidator = $('#fastAddSimForm').data('bootstrapValidator');
	        bootstrapValidator.validate();
	        if(bootstrapValidator.isValid()){
	        	saveAddSim();
	        }
		 });	    
		 onLoadCompanyTree();
	});
   function showDialog(opStr, id, installFlag){
	   $("#infoId").val(id);
	   $("#device_id").removeAttr("disabled");
	   $("#company_id").removeAttr("disabled");
	   $("#company_name").removeAttr("disabled");
	   if(opStr=="insert"){
		   $("#infoModalTitle").text("添加设备信息");
	   }
	   if(opStr=="update"){
		   $("#infoModalTitle").text("编辑设备信息");
		   $("#device_id").attr("disabled","disabled");
		   if(installFlag==1){
			   $("#company_id").attr("disabled","disabled");
			   $("#company_name").attr("disabled","disabled");
		   }
		   $("#company_name").removeAttr("onclick");
		   $("#company_name").attr("disabled","disabled");
		   
	   }
	    $.ajax({
	        url: "${request.contextPath}/device/showDetail",
	        type: "post",
	        async: false,
	        data: {id:id},
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success && data.msg){
	            		//设备类型
	            		var deviceAry = data.msg.deviceType;
	            		if(deviceAry && deviceAry.length>0){
	            			$("#device_type").empty();
	            			for(var i=0;i<deviceAry.length;i++){
	            				$("#device_type").append("<option value='"+deviceAry[i].key+"'>"+deviceAry[i].value+"</option>");
	            			}
	            			$("#device_type").val(3);
	            		}
	            		//厂家类型
	            		var factoryAry = data.msg.factoryType;
	            		if(factoryAry && factoryAry.length>0){
	            			$("#factory_type").empty();
	            			for(var i=0;i<factoryAry.length;i++){
	            				$("#factory_type").append("<option value='"+factoryAry[i].key+"'>"+factoryAry[i].value+"</option>");
	            			}
	            			$("#factory_type").val(1);
	            		}
	            		var item = data.msg.item;
	            		$("#device_id").val(item.device_id);
	            		console.log("company_id---->>>"+(item.company_id+"_"+item.company_name));
	            		console.log("sim_id---->>>"+(item.sim_id+"_"+item.sim_card));
	            		if(id=="-1"){
	            			$("#sim_id").val("");
	            			$("#old_sim_id").val("");
	            			$("#company_id").val("");
	            			$("#company_name").val("");
	            		}else{
	            			$("#sim_id").val(item.sim_id);
	            			$("#old_sim_id").val(item.sim_id);
	            			$("#sim_card").val(item.sim_card);
	            			$("#company_id").val(item.company_id);
	            			$("#company_name").val(item.company_name);
	            		}
	            		$("#serial_id").val(item.serial_id);
	            		$("#brand").val(item.brand);
	            		$("#model").val(item.model);
	            		$("#software_ver").val(item.software_ver);
	            		$("#hardware_ver").val(item.hardware_ver);
	            		$("#product_manufacturer").val(item.product_manufacturer);
	            		$("#remark").text(item.remark);
	            		if(id!="-1"){
	            			$("#device_type").val(item.device_type);
	            			$("#factory_type").val(item.factory_type);
	            		}
	            		$("#infoModal").modal('show');
	            	}else{
	            		alert("数据出错!");
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	   });
   }
   function saveInfo(){
	    var device_id = $.trim($("#device_id").val());
	    var company_id = $.trim($("#company_id").val());
	    var device_type = $.trim($("#device_type").val());
	    var serial_id = $.trim($("#serial_id").val());
		var sim_id = $.trim($("#sim_id").val());
		var factory_type = $.trim($("#factory_type").val());
		var brand = $.trim($("#brand").val());
		var model = $.trim($("#model").val());
		var software_ver = $.trim($("#software_ver").val());
		var hardware_ver = $.trim($("#hardware_ver").val());
		var product_manufacturer = $.trim($("#product_manufacturer").val());
		var remark = $.trim($("#remark").val());
	    var data = {id:$("#infoId").val(), device_id:device_id, company_id:company_id, serial_id:serial_id, device_type:device_type, 
	    		sim_id:sim_id, factory_type:factory_type, brand:brand, model:model, software_ver:software_ver, hardware_ver:hardware_ver, 
	    		product_manufacturer:product_manufacturer, remark:remark, old_sim_id:$("#old_sim_id").val()};
	    $.ajax({
	        url: "${request.contextPath}/device/saveOrUpdateInfo",
	        type: "post",
	        async: false,
	        data: data,
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success){
	            		location.reload();
	            	}else{
	            		alert(data.msg);
	            		$("#device_id").focus();
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	    });
   }
   function deleteInfoInList(id){
	   if(id){
		   CvMsg.confirm("警告","数据删除后将无法还原！是否删除？",function(){
			   $.ajax({
					url : "${request.contextPath}/device/deleteInfo",
					type : "post",
					data : {id:id},
					success : function(data) {
						if (data.success) {
							location.reload();
						} else {
		            		alert("数据出错!");
		            		return false;
						}
					}
				}); 
		   });
	   }
   }
   function onLoadCompanyTree(){
	   $.ajax({
			url : "${request.contextPath}/user/getTreeOrg",
			type : "post",
			success : function(data) {
				if (data.success && data.other) {
				   var setting = {
				   		view: {
				   			dblClickExpand: true
				   		},
				   		data: {
				   			simpleData: {
				   				enable: true
				   			}
				   		},
				   		callback: {
				   			onClick: onClick
				   		}
				   	};
				   var treeData = formatTreeImage(data.other);
			       $.fn.zTree.init($("#treeDemo"), setting, treeData);
			       $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);//展开
				}
			}
		});
   }
  	function onClick(e, treeId, treeNode) {
   		var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
   		nodes = zTree.getSelectedNodes(),
   		v = "";
   		pv = "";
   		nodes.sort(function compare(a,b){return a.id-b.id;});
   		for (var i=0, l=nodes.length; i<l; i++) {
   			v += nodes[i].name + ",";
   			pv += nodes[i].id + ",";
   		}
   		if (v.length > 0 ) v = v.substring(0, v.length-1);
   		$("#company_name").val(v);
   		
   		if (pv.length > 0 ) pv = pv.substring(0, pv.length-1);
   		$("#company_id").val(pv);
 
   		//移除校验
   		$('#defaultForm').data('bootstrapValidator')
        .updateStatus('company_name', 'NOT_VALIDATED', null)
        .validateField('company_name');
   		
   		hideMenu();
   	}
  	function showMenu() {
   		var cityObj = $("#pid");
   		var cityOffset = $("#pid").offset();
   		$("#menuContent").slideDown("fast");
   		$("body").bind("mousedown", onBodyDown);
   	}
   	function hideMenu() {
   		$("#menuContent").fadeOut("fast");
   		$("body").unbind("mousedown", onBodyDown);
   	}
   	function onBodyDown(event) {
   		if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
   			hideMenu();
   		}
   	}
    //打开 选择sim卡信息 对话框
   	function openSimList(){
    	$("#simListModal").modal('show');
    	$("#simList tbody").empty();
	    $.ajax({
	        url: "${request.contextPath}/sim/getSimList",
	        type: "post",
	        async: false,
	        success: function (data) {
	        	if(data){
	            	data = eval(data);
	            	if(data.success && data.msg){
	            		var item = data.msg;
	            		var html = "";
	            		for(var i=0;i<item.length;i++){
	            			html+="<tr><td>"+(i+1)+"</td><td>"+item[i].sim_card+"</td>"+"<td>"+item[i].company_name+"</td><td><input onClick='selSim("+item[i].id+",\""+item[i].sim_card+"\")' name='simCheckRedio' type='radio' class='minimal' value='"+item[i].id+"'/></td></tr>";
	            		}
	            		console.log(html);
	            		$("#simList tbody").html(html);
	            	}
	            }
	        },
	        error: function () { }
	    });
   	}
    //从sim卡列表中选择一条数据
    function selSim(selSimId,selSimCard){
    	if(selSimId){
    		$("#sim_id").val(selSimId);
    		$("#sim_card").val(selSimCard);
    		$("#simListModal").modal('hide');
    	}
    }
    //打开增加sim卡的对话框
    function showAddSim(){
    	var company_id = $.trim($("#company_id").val());
    	if(!company_id && company_id!="0"){
	    	alert("请选择所属公司！");
	    	return false;
	    }
    	$("#addSimModal").modal('show');
    }
    //增加sim卡的对话框 中的“保存”操作
    function saveAddSim(){
	    var add_sim_card = $.trim($("#add_sim_card").val());
	    var company_id = $.trim($("#company_id").val());
	    var data = {sim_card:add_sim_card, company_id:company_id};
	    $.ajax({
	        url: "${request.contextPath}/sim/fastSaveSim",
	        type: "post",
	        async: false,
	        data: data,
	        success: function (data) {
	        	debugger;
	        	if(data){
	            	data = eval(data);
	            	if(data.success){
	            		var item = data.msg;
	            		$("#sim_id").val(item.id);
	            		$("#sim_card").val(item.sim_card);
	            		$("#addSimModal").modal('hide');
	            	}else{
	            		alert(data.msg);
	            		$("#sim_card").focus();
	            		return false;
	            	}
	            }
	        },
	        error: function () { }
	    });   	
    }
</script>
